//
//  YWAssetsInventoryDetailsTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/10/25.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAssetsInventoryDetailsTableViewController.h"
#import "YWSelectContactTableViewController.h"
#import "YWNoReadReplyTableViewController.h"
//#import "YWNoQrcodeLedgerViewController.h"
#import "YWLedgerViewController.h"

#import "YWAssetsInventoryDetailHeadTableViewCell.h"
#import "YWAssetsEquipmentListTableViewCell.h"
#import "YWNewCommentCell.h"

#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MBProgressHUD.h"
#import "UIView+Extension.h"
#import "YWConst.h"
#import "YWCommonTool.h"

#import "YWReply.h"
#import "YWReplyManager.h"
#import "YWHandler.h"
#import "YWAssetCheckRecord.h"
#import "YWAssetCheckRecordDetails.h"
#import "YWLocation.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWAssetCheckManager.h"

@interface YWAssetsInventoryDetailsTableViewController ()<UITextFieldDelegate,YWContactVCSelectContactDelegate>
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) YWHandler *atUser;
/** 回复栏 */
@property (nonatomic, copy) NSString* content;
@property (nonatomic, strong) UIButton * selectButton;//选择抄送人
@property (nonatomic, strong) NSArray<YWReply *>* replyArray;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@property (nonatomic, strong) UIView *replyView;
@end

@implementation YWAssetsInventoryDetailsTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"清点详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backToCheckRecordListView:)];
    [self initTableView];
    [self requestReplyData];
}

- (void)initTableView{
    [self.tableView registerClass:[YWAssetsInventoryDetailHeadTableViewCell class] forCellReuseIdentifier:YWAssetsInventoryDetailHeadTableViewCellIdentifier];
    [self.tableView registerClass:[YWAssetsEquipmentListTableViewCell class] forCellReuseIdentifier:YWAssetsEquipmentListTableViewCellIdentifier];
    [self.tableView registerClass:[YWNewCommentCell class] forCellReuseIdentifier:YWNewCommentCellIdetifer];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 46, 0);
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.navigationController.view addSubview:self.replyView];
}

- (void)requestReplyData{
    YWWeakSelf(weakSelf);
    [[YWReplyManager shareManager] requestReplysWithRelationId:@(weakSelf.checkRecord.checkRecordId).stringValue type:YWReplyRelationTypeAssetCheckRecord WithComplete:^(BOOL success) {
        weakSelf.replyArray = nil;
        [weakSelf.tableView reloadData];
    }];
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        //从数据库中取得回复数据，增加清点回复类型
         NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:self.checkRecord.checkRecordId andRelationType:YWReplyRelationTypeAssetCheckRecord];
        _replyArray = commentArray;
    }
    return _replyArray;
}

- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-46, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH)];
    self.textField.placeholder = @"回复";
    [self.textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.textField.delegate = self;
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)selectSingleContact:(YWHandler*)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return self.checkRecord.recordDetails.count;
    }else if (section == 2){
        return self.replyArray.count;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWAssetsInventoryDetailHeadTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWAssetsInventoryDetailHeadTableViewCellIdentifier];
        [self configureAssetsInventoryListCell:cell atIndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 1){
        YWAssetsEquipmentListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWAssetsEquipmentListTableViewCellIdentifier];
        [self configureAssetsEquipmentListCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        YWNewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:YWNewCommentCellIdetifer];
        [self configureCommentCell:cell atIndexPath:indexPath];
        return cell;
    }
}

//计算cell高度
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section==0) {
//        return [tableView fd_heightForCellWithIdentifier:YWAssetsInventoryDetailHeadTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWAssetsInventoryDetailHeadTableViewCell *cell) {
//            [self configureAssetsInventoryListCell:cell atIndexPath:indexPath];
//        }];
//    }else if (indexPath.section == 1){
//        return [tableView fd_heightForCellWithIdentifier:YWAssetsEquipmentListTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWAssetsEquipmentListTableViewCell *cell) {
//            [self configureAssetsEquipmentListCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWNewCommentCellIdetifer cacheByIndexPath:indexPath configuration:^(YWNewCommentCell *cell) {
//            [self configureCommentCell:cell atIndexPath:indexPath];
//        }];
//    }
//}

- (void)configureAssetsInventoryListCell:(YWAssetsInventoryDetailHeadTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.checkRecord = self.checkRecord;
}

- (void)configureAssetsEquipmentListCell:(YWAssetsEquipmentListTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.equipmentList = self.checkRecord.recordDetails[indexPath.row];
}

- (void)configureCommentCell:(YWNewCommentCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWReply *reply = self.replyArray[indexPath.row];
    cell.reply = reply;
    //除了第一条评论则隐藏最左边评论图标
    [cell viewWithTag:101 ].hidden = indexPath.row == 0 ? NO : YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark - table view section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWAssetsInventoryDetailsTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
    }
    if (section == 1) {
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2016;
        label.numberOfLines = 0;
        label.font = KTitleFont;
        [headerView addSubview:label];
        
        UIButton * ledgerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        ledgerBtn.frame = CGRectMake(SCREEN_WIDTH/2+25, 0, SCREEN_WIDTH/2-25*2, 25);
        ledgerBtn.tag = 2017;
        [ledgerBtn setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        ledgerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        ledgerBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        [ledgerBtn addTarget:self action:@selector(ledgerButtonActionEvent:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:ledgerBtn];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    NSString * buttonTitle = [self buttonTitleForHeaderInSection:section];
    UIButton * button = [headerView viewWithTag:2017];
    [button setTitle:buttonTitle forState:UIControlStateNormal];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH/2-15*2, 25);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        return @"设备清单";
    }else{
        return nil;
    }
}

- (NSString *)buttonTitleForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return @"设备台账";
    }else{
        return nil;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 25;
    }else{
        return 0.01;
    }
}

- (void)ledgerButtonActionEvent:(UIButton*)sender{
    [self.navigationController.view endEditing:YES];
    YWLedgerViewController * noQrcodeLedger = [[YWLedgerViewController alloc] init];
    noQrcodeLedger.locationId = self.checkRecord.location.locationId;
    [self.navigationController pushViewController:noQrcodeLedger animated:YES];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

#pragma mark -----post reply

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectContactTableViewController * selectContactVC = [[YWSelectContactTableViewController alloc] init];
    selectContactVC.delegate = self;
    YWBuilding *building = [[YWBuildingManager shareManager] buildingWithLocationId:self.checkRecord.location.locationId];
    selectContactVC.buildingId = building.buildingId;
    selectContactVC.isMultiSelect = NO;
    selectContactVC.ownContacts = self.atUser ? @[self.atUser] :nil;
    selectContactVC.titleName = @"选择@人";
    [self.navigationController pushViewController:selectContactVC animated:YES];
}

- (void)textFieldChange:(UITextField*)textfield{
    NSString *toBeString = textfield.text;
    //获取高亮部分
    UITextRange *selectedRange = [textfield markedTextRange];
    UITextPosition *position = [textfield positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > 100)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:100];
            if (rangeIndex.length == 1)
            {
                textfield.text = [toBeString substringToIndex:100];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 100)];
                textfield.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:@"请填写回复内容"];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:@"回复内容不超过100字"];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    _content = textField.text;
    [[YWAssetCheckManager shareManager] postCheckRecordReplyWithReply:[self createReply] atUser:self.atUser WithComplete:^(BOOL success){
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:@"回复成功"];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            textField.text = @"";
            _replyArray = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = _checkRecord.checkRecordId;
    reply.relationType = YWReplyRelationTypeAssetCheckRecord;
    reply.content = _content;
    return reply;
}

- (void)backToCheckRecordListView:(id)sender{
    [self.replyView removeFromSuperview];
    UIViewController *vc = nil;
    for (UIViewController *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[YWNoReadReplyTableViewController class]]) {
            vc = temp;
            break;
        }
    }
    if (vc) {
        [self.navigationController popToViewController:vc animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark ----- 有关键盘

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46;
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.replyView.hidden = YES;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
